
package structure;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * Implement un DataCenter basé sur les map.
 * 
 * @author David Bernard
 * @since java 1.6
 * @see Map
 */
public class MapDataCenter extends AbstractDataCenter
{
	private Map<DataKey, DataNode> map;

	/**
	 * Instancie un DataCenter basé sur une hashtable.
	 */
	public MapDataCenter()
	{
		this(Structure.Hashtable.name());
	}

	/**
	 * Instancie un DataCenter basé sur un type.
	 * 
	 * @param type String, un type de map.
	 */
	public MapDataCenter(String type)
	{
		boolean ok = this.setMapType(type);

		if (!ok)
		{
			throw new RuntimeException("paramètre invalide");
		}
	}

	private boolean setMapType(String nomStructure)
	{
		Structure structure = Structure.trouverAvecNom(nomStructure);
		boolean ok = structure != null;

		if (ok)
		{
			if (structure == Structure.HashMap)
			{
				this.map = new HashMap<DataKey, DataNode>();
			}
			else if (structure == Structure.TreeMap)
			{
				this.map = new TreeMap<DataKey, DataNode>();
			}
			else if (structure == Structure.Hashtable)
			{
				this.map = new Hashtable<DataKey, DataNode>();
			}
			else
			{
				ok = false;
			}
		}

		return ok;
	}

	@Override
	public Iterator<DataNode> iterator()
	{
		return this.map.values().iterator();
	}

	@Override
	public int size()
	{
		return this.map.size();
	}

	@Override
	public void removeAllData()
	{
		this.map.clear();
		System.gc();
	}

	@Override
	protected void setElement(DataNode node)
	{
		this.map.put(node.createKey(), node.createNode());
	}

	@Override
	protected DataNode getElement(DataKey cle)
	{
		return this.map.get(cle);
	}

	@Override
	protected void removeElement(DataKey referenceNode)
	{
		this.map.remove(referenceNode);
	}

	/**
	 * Valide le type de structure.
	 * 
	 * @param type String, le type de structure à valider.
	 * 
	 * @return boolean, vrai si valide.
	 */
	public static boolean validerType(String type)
	{
		return (type != null)
				&& (type.equalsIgnoreCase(Structure.HashMap.name())
						|| type.equalsIgnoreCase(Structure.TreeMap.name()) || type
							.equalsIgnoreCase(Structure.Hashtable.name()));
	}
}
